package com.wukang.photovoltaicinspectionpictures.utils

import android.content.Context
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.MainThread
import com.google.android.material.snackbar.BaseTransientBottomBar.Duration
import com.wukang.photovoltaicinspectionpictures.logger.Rog
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/* ------------------------------- kotlin中使用的扩展方法 ------------------------------- */

/**
 * toast展示
 * - 参数为[Int]，则展示R.string资源内容
 * - 其他参数展示自身[Any.toString]方法转化后的内容
 */
@MainThread
fun <T> T?.toast(context: Context, @Duration duration: Int = Toast.LENGTH_SHORT) = if (this is Int) {
    Toast.makeText(context, this, duration).show()
} else {
    Toast.makeText(context, this.toString(), duration).show()
}

/**
 * 打印[Log.VERBOSE]级别日志
 */
fun <T> T?.logV(tag: String? = null, fn: ((T?) -> String)? = null): T? {
    Rog.v(tag, fn?.invoke(this) ?: this.toString())
    return this
}

/**
 * 打印[Log.DEBUG]级别日志
 */
fun <T> T?.logD(tag: String? = null, fn: ((T?) -> String)? = null): T? {
    Rog.d(tag, fn?.invoke(this) ?: this.toString())
    return this
}

/**
 * 打印[Log.INFO]级别日志
 */
fun <T> T?.logI(tag: String? = null, fn: ((T?) -> String)? = null): T? {
    Rog.i(tag, fn?.invoke(this) ?: this.toString())
    return this
}

/**
 * 打印[Log.WARN]级别日志
 */
fun <T> T?.logW(tag: String? = null, fn: ((T?) -> String)? = null): T? {
    Rog.w(tag, fn?.invoke(this) ?: this.toString())
    return this
}

/**
 * 打印[Log.ERROR]级别日志
 */
fun <T> T?.logE(tag: String? = null, fn: ((T?) -> String)? = null): T? {
    Rog.e(tag, fn?.invoke(this) ?: this.toString())
    return this
}

/**
 * 时间戳转化为日期字符串
 */
fun Long.formatToDateString(): String = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(this))

/**
 * 时间戳转化为时间字符串
 */
fun Long.formatToTimeString(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date(this))

/**
 * 快速生成list
 */
inline fun <T> Int.buildList(builder: (Int) -> T): List<T> {
    if (this <= 0) {
        return emptyList()
    }
    return (0..this).map { builder(it) }.toList()
}

/**
 * 防抖点击监听
 */
inline fun View.onDebounceClick(interval: Long = 1000L, crossinline onClick: (View) -> Unit) {
    setOnClickListener(object : DebounceListener(interval) {
        override fun onDebounceClick(v: View) {
            onClick(v)
        }
    })
}